package com.heima.cn;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/RequestServletDemo02")
public class RequestDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //题目：将图片响应在游览器上
        //根据相对路径，得到发布的绝对路径
        String realPath = getServletContext().getRealPath("/img/itheima.png");
        //从本地将图片读取到内存中
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
        //创建响应流对象将图片响应到游览器上
        ServletOutputStream os = resp.getOutputStream();
        byte[] arr = new byte[1024];
        int len ;
        while((len=bis.read(arr))!=-1){
            os.write(arr,0,len);
        }
        bis.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
